﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BingVis.GoogleTransit;
using BingVis.WPFClient;
using System.IO;
using System.Threading;
using System.Diagnostics;
using BingVis.Common;

namespace BingVis.UtilityApp
{
    public class StopTimeEqualityComparer : IEqualityComparer<ITransitStopTime>
    {

        #region IEqualityComparer<ITransitStopTime> Members

        public bool Equals(ITransitStopTime x, ITransitStopTime y)
        {
            return (x.Stop.Name == y.Stop.Name);
        }

        public int GetHashCode(ITransitStopTime obj)
        {
            return obj.GetHashCode();
        }

        #endregion
    }


    class Program
    {
        static string fileDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles");

        static void Main(string[] args)
        {
            // Compress a test file...
            //CompressFareFile(Path.Combine(fileDir, "FareFile.txt"), Path.Combine(fileDir, "FareFile_comp.txt"));

            // Create The Stop / Route Lookup files.
            //CreateStopColorFiles();

            // Create a Stop to Color Lookup
            PackageLoader loader = new PackageLoader();
            var files = loader.ParseFiles(new DirectoryFileLoader(Path.Combine(fileDir, "StopColors")));

            Dictionary<string, List<string>> stopColors = new Dictionary<string, List<string>>();
            foreach (var file in files)
            {
                foreach (var line in file.Lines)
                {
                    var vals = line.Split(",".ToCharArray());
                    string stopName = string.Empty;
                    string color;
                    if (vals.Count() > 2)
                    {
                        color = vals[vals.Length - 1];
                        vals.Take(vals.Length - 1).ToList().ForEach(x => stopName += x);                        
                    }
                    else
                    {
                        color = vals[1];                        
                        stopName = vals[0];
                    }

                    stopName = StopNameLookup.GetStopName(stopName);

                    if (!stopColors.ContainsKey(stopName))
                    {
                        stopColors.Add(stopName, new List<string>() { color });
                    }
                    else
                    {
                        if (!stopColors[stopName].Contains(color))
                            stopColors[stopName].Add(color);
                    }
                }
            }

            //Dictionary<string, List<string>> stopColorLookup = new Dictionary<string, List<string>>()
            //{
            //    { "asldkfj", new List<string>() { "alsdkfj", "asldkfj" } },
            //};

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("private Dictionary<string, List<string>> stopColorLookup = new Dictionary<string, List<string>>()");
            sb.AppendLine("{");
            
            foreach (var key in stopColors.Keys)
            {
                var colors = string.Empty;
                stopColors[key].ForEach(x => colors += "\"" + x + "\",");
                sb.AppendLine(String.Format(@"{{ ""{0}"", new List<string>() {{ {1} }} }},", key, colors));
            }
            sb.AppendLine("};");
            File.WriteAllText("c:\\StopColors.txt", sb.ToString());
        }

        static void CompressFareFile(string fareFilePath, string compressFilePath)
        {  
            bool done = false;
            FareFileCompressor.CompressFareFile(fareFilePath, compressFilePath, x => done = true);
            while (!done) { Console.WriteLine("Processing..."); Thread.Sleep(1000); }
        }

        static void CreateStopColorFiles()
        {
            PackageLoader loader = new PackageLoader();
            var files = loader.ParseFiles(new DirectoryFileLoader(fileDir));

            var stopFile = files.First(f => f.FileName == "stops.txt");
            var routeFile = files.First(f => f.FileName == "routes.txt");
            var tripsFile = files.First(f => f.FileName == "trips.txt");
            var stopTimesFile = files.First(f => f.FileName == "stop_times.txt");

            Console.WriteLine("Loading Stops...");
            var stopLoader = new TransitStopLoader(stopFile);
            stopLoader.ProcessFile();
            while (stopLoader.Processing) { Thread.Sleep(100); }

            Console.WriteLine("Loading Stop Times...");
            var stopTimesLoader = new TransitStopTimeLoader(stopTimesFile, stopLoader.Items);
            stopTimesLoader.ProcessFile();
            while (stopTimesLoader.Processing) { Thread.Sleep(1000); Console.WriteLine(" - {0} Items ", stopTimesLoader.Items.Count); }

            Console.WriteLine("Loading Trips...");
            var tripsLoader = new TransitTripLoader(tripsFile, stopTimesLoader.Items);
            tripsLoader.ProcessFile();
            while (tripsLoader.Processing) { Thread.Sleep(1000); }

            Console.WriteLine("Loading Routes...");
            var routeLoader = new TransitRouteLoader(routeFile, tripsLoader.Items);
            routeLoader.ProcessFile();
            while (routeLoader.Processing) { Thread.Sleep(1000); }

            Console.WriteLine();

            StringBuilder sb = new StringBuilder();
            // Trying to break it up.
            foreach (var route in routeLoader.Items)
            {
                var routeStops = (from trip in route.Trips
                                  from stopTime in trip.StopTimes.Distinct(new StopTimeEqualityComparer())
                                  select new
                                  {
                                      Stop = stopTime.Stop.Name,
                                      Color = route.ColorHex
                                  })
                                 .Distinct();

                sb.Remove(0, sb.Length);

                foreach (var rs in routeStops)
                {
                    Console.WriteLine(string.Format("{0},#{1}", rs.Stop, rs.Color));
                    sb.AppendLine(string.Format("{0},#{1}", rs.Stop, rs.Color));
                }

                File.WriteAllText(String.Format(@"c:\StopColors_{0}.txt", route.Id), sb.ToString());
            }
        }
    }
}
